﻿using CL.Business.BLL;
using CL.Business.Entity;
using CL.Tools.Common;
using CL.View.Entity.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CL.Admin.admin.promotion
{
    public partial class Commission_settlement : UI.AdminPage
    {
        protected string userName = string.Empty;
        protected string month = string.Empty;
        protected int totalCount;
        protected int page;
        protected int pageSize;
        public static SettleMonthBLL bll = new SettleMonthBLL();       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.userName = QPRequest.GetQueryString("userName");
                this.month = QPRequest.GetQueryString("month");
                if (string.IsNullOrEmpty(month))
                    txtMonth.Text = month = DateTime.Now.ToString("yyyy-MM");
                this.pageSize = GetPageSize(20);
                RptBind(this.userName, this.month);
            }
        }

        private void RptBind(string _userName, string _month)
        {
            this.page = QPRequest.GetQueryInt("page", 1);
            this.txtKeywords.Text = _userName;
            this.txtMonth.Text = _month;
            this.rptList.DataSource = bll.QueryCommission(_userName, _month, this.page, this.pageSize, ref this.totalCount);
            this.rptList.DataBind();
            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, GetUrl(), 8);
        }

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("Commission_settlement_page_size", "QPcmsPage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion


        protected string GetUrl()
        {
            return Utils.CombUrlTxt("Commission_settlement.aspx", "userName={0}&month={1}&page={2}", txtKeywords.Text, txtMonth.Text, "__id__");
        }

        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("Commission_settlement_page_size", "QPcmsPage", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(GetUrl());
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetUrl());
        }

        protected void btnMonthChange_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetUrl());
        }

        protected void lbtnExport_Click(object sender, EventArgs e)
        {
            List<udv_SettleMonth> list = bll.QueryCommission(this.txtKeywords.Text, this.txtMonth.Text, 1, 20, ref this.totalCount);
            StringBuilder mystringbuilder = new StringBuilder();
            mystringbuilder.Append("<table border = '1' ><tr><td align = 'center' colspan=\"7\"> <b> 佣金结算导出表 </b></td></tr> ");
            mystringbuilder.Append("<tr><td align='center'><b>序号</b></td><td align='center'><b>代理账号</b></td><td align='center'><b>月份</b></td><td align='center'><b>月销售总额(单位：元)</b></td>");
            mystringbuilder.Append("<td align='center'><b>结算日期</b></td><td align='center'><b>结算点位</b></td><td align='center'><b> 结算金额(元)</b></td><td align='center'><b> 银行名称</b></td><td align='center'><b> 银行卡号</b></td>");
            mystringbuilder.Append("</tr>");
            if (list == null && list.Count <= 0)
            {
                return;
            }
            for (int i = 0; i < list.Count; i++)
            {
                mystringbuilder.Append("<tr>");
                mystringbuilder.Append("<td>" + (i + 1).ToString() + "</td>");
                mystringbuilder.Append("<td>" + list[i].AccountCode + "</td>");
                mystringbuilder.Append("<td>" + list[i].Month + "</td>");
                mystringbuilder.Append("<td>" + Math.Round((double)list[i].BuyMount  / 100, 2) + "</td>");
                mystringbuilder.Append("<td>" + list[i].SettleTime + "</td>");
                mystringbuilder.Append("<td>" + list[i].RebateNum + "</td>");
                mystringbuilder.Append("<td>" + Math.Round((double)list[i].SettleAmount/10000/100, 2) + "</td>");
                mystringbuilder.Append("<td>" + list[i].BankName + "</td>");
                mystringbuilder.Append("<td>" + list[i].BankCard + "</td>");
                mystringbuilder.Append("</tr>");
            }
            mystringbuilder.Append("</table>");
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("佣金结算", Encoding.UTF8) + ".xls");
            Response.Write(mystringbuilder.ToString());
            Response.Flush();
            Response.End();
        }
        //结算
        protected void lbtnBalance_Click(object sender, EventArgs e)
        {
           
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                var SettleMonth = bll.QueryEntity(id);
                if (cb.Checked&&SettleMonth!=null)
                {
                    SettleMonth.SettleTime = DateTime.Now;
                    SettleMonth.SettleStatus = 1;
                    if (bll.ModifyEntity(SettleMonth) > 0)
                    {                     
                        new RecordBLL().InsertEntity(new RecordEntity()
                        {
                            AccountID = SettleMonth.AccountID,
                            RecordTime = DateTime.Now,
                            RecordRemark = string.Format("{0}月佣金结算",SettleMonth.Month),
                            RecordType = 6
                        });
                        JscriptMsg("结算成功！", GetUrl());
                    }
                    else
                    {
                        JscriptMsg("结算失败！", GetUrl());
                    }
                }
            }
        }
        //审核
        protected void lbtnAduit_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                var SettleMonth = bll.QueryEntity(id);
                if (cb.Checked&&SettleMonth!=null)
                {
                    if (SettleMonth.SettleStatus != 1)
                    {
                        JscriptMsg("佣金结算之后才能审核！", GetUrl());
                        return;
                    }
                    if (SettleMonth.SettleStatus == 1)
                    {
                        SettleMonth.SettleStatus = 2;
                        if (bll.ModifyEntity(SettleMonth) > 0)
                        {
                            JscriptMsg("审核成功！", GetUrl());
                        }
                        else
                        {
                            JscriptMsg("审核失败！", GetUrl());
                        }
                    }
                }
            }
        }
        //打款发通知
        protected void lbtnCharge_Click(object sender, EventArgs e)
        {
            NoticeBLL notice = new NoticeBLL();
            NoticeEntity entity = new NoticeEntity();
            var month = ""; int accountid = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                var settleMonth = bll.QueryEntity(id);
                if (cb.Checked&& settleMonth != null)
                {
                    if (settleMonth.SettleStatus == 2)
                    {
                        settleMonth.SettleStatus = 3;
                        month = settleMonth.Month;
                        accountid = settleMonth.AccountID;
                        int recordCount = bll.ModifyEntity(settleMonth);
                        if (recordCount > 0)
                        {
                            JscriptMsg("佣金发放成功！", GetUrl());
                        }
                        //统计推广员累计佣金
                        int totalAmount = new SettleMonthBLL().CalTotalAmount(accountid);
                        AccountEntity account=  new AccountBLL().QueryEntity(accountid);
                        account.TotalAmount = totalAmount;                    
                        new AccountBLL().UpdateEntity(account);

                        entity.AccountID = accountid;
                        entity.IsRead = false;
                        entity.NoticeType = 1;
                        entity.ReadTime = DateTime.Now.AddMinutes(30);
                        entity.SendTime = DateTime.Now;
                        var lastMonth = DateTime.Now.AddMonths(-1);
                        entity.NoticeTitle = lastMonth.ToString("yyyy-MM") + "联盟结算通知";
                        entity.NoticeContent = "尊敬的推广员 {0} 你好，{1}（{2}--{3}）的推广收益已经结算完成。你的本期收益为{4}元，联盟已经自动打款到位数为{5}的{6}的银行卡上。若有疑问，请联系网站客服";
                        entity.NoticeContent = string.Format(entity.NoticeContent,
                            account.AccountCode,
                            lastMonth.ToString("yyyy-MM"),
                            new DateTime(lastMonth.Year, lastMonth.Month, 1).ToString("yyyy-MM--dd"),
                            new DateTime(lastMonth.Year, lastMonth.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy-MM--dd"),
                            Math.Round((double)settleMonth.SettleAmount / 1000000, 2).ToString(),
                            account.BankCard.Substring(account.BankCard.Length - 4, 4),
                            account.BankName
                            );

                        if (notice.InsertNotice(entity) > 0)
                        {
                            JscriptMsg("通知成功！", GetUrl());
                        }
                        else
                        {
                            JscriptMsg("通知失败！", GetUrl());
                        }
                    }
                    else
                    {
                        JscriptMsg("先通过审核再结算!", GetUrl());
                    }
                }
            }
        }
    }
}